package com.company;

import java.lang.reflect.Array;
import java.util.ArrayDeque;
import java.util.Queue;

/**
 * @author zhf
 * @date 2022/1/20
 */
//通过数组建立一颗二叉树
public class TreeUtil {
    public static TreeNode CreateTree(Integer[] arr){
        if (arr == null) {
            return null;
        }
        TreeNode root = new TreeNode(arr[0]);
        ArrayDeque<TreeNode> queue = new ArrayDeque<>();
        queue.add(root);
        boolean isLeft = true;
        for (int i = 1; i < arr.length; i++) {
            TreeNode node = queue.peek();
            if (isLeft) {
                if (arr[i] != null) {
                    node.left = new TreeNode(arr[i]);
                    queue.offer(node.left);
                }
                isLeft = false;
            }else {
                if (arr[i] != null){
                    node.right = new TreeNode(arr[i]);
                    queue.offer(node.right);
                }
                queue.poll();
                isLeft = true;
            }
        }
        return root;
    }

}
